<?php
namespace app\admin\model;

use app\common\model\User as UserModel;
use hema\wechat\Wechat as Wx;

/**
 * 用户模型
 */
class User extends UserModel
{
	/**
	 * 关注公众号
	 */
	public function subscribe(array $data)
	{
	    $wx = new Wx;
	    if($result = $wx->getUserInfo($data['FromUserName'])){
	        $userInfo = [
	            'nickname' => '微信用户',
                'wx_open_id' => $result['openid'],
                'is_wechat' => 1,
            ];
            //判断是否 开启UnionID机制
	        isset($result['unionid']) && $userInfo['union_id'] = $result['unionid'];
	        
	        if(!$wxUser = $this->where('wx_open_id',$result['openid'])->find()){
	            $wxUser = $this;
	        }
    	    return $wxUser->save($userInfo);
	    }
	    return false;
	}
	
	/**
	 * 取消关注公众号
	 */
	public function unsubscribe(array $data)
	{
	    if($wxUser = $this->where('wx_open_id',$data['FromUserName'])->find()){
            $wxUser->is_wechat = 0;
            return $wxUser->save();
        }
        return false;
	}
}
